//
//  HJOAuthViewController.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/25.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit
import SVProgressHUD


class HJOAuthViewController: UIViewController {

    lazy var webview = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //不透明,解决webview没有数据的时候底部会出现黑色
        webview.isOpaque = false
        //设置背景颜色
        view.backgroundColor = UIColor.white
        //设置代理
        webview.delegate = self
        
        view = webview
        
        //加载导航栏关闭按钮
        setNavBar()
        
        //加载webView
        loadOAuthPage()
        
    }
    // 设置导航栏关闭按钮
    func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        //上线的时候一定要注意将方法 注销掉
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(fillAccount))
    }
   
     @objc private func fillAccount() {
         //webView执行js
       //let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' "
        let jsString = "document.getElementById('userId').value = '3053337146@qq.com', document.getElementById('passwd').value = 'xhj110' "
        
        webview.stringByEvaluatingJavaScript(from: jsString)
    }
    
   @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        
        //webview加载页面
        webview.loadRequest(request)
    }
    
   
}


extension HJOAuthViewController:UIWebViewDelegate{
    //开始加载界面
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    //界面加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //网页每次加载新的页面实际上都是重写发送了request请求,在该方法中就可以拦截该请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString ?? ""
        
       // print(urlString)
        
        let flag = "code="
        
        if urlString.contains(flag) {
          //获取url的参数部分
            let query = request.url?.query ?? ""
           // print(query)
            
          
            let code = (query as NSString).substring(from: flag.characters.count)
            
            HJUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code: code, finished: { (success) in
                
                if !success {
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
   
               // print("chenggong")
                //Mark:发布通知,第一次登陆显示登录界面
                NotificationCenter.default.post(name: NSNotification.Name(KchangeRootViewController), object: "welcome")
            })
             return false
        }
        
        return true
    }
}
